<template>
  <div class="automation-import">
    <el-card>
      <template #header>
        <span>手动导入</span>
      </template>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        style="max-width: 600px"
      >
        <el-form-item label="导入配置" prop="configId">
          <el-select
            v-model="formData.configId"
            placeholder="请选择导入配置"
            style="width: 100%"
            :loading="configLoading"
          >
            <el-option
              v-for="config in configList"
              :key="config.id"
              :label="config.name"
              :value="config.id!.toString()"
            >
              <div class="flex items-center justify-between">
                <div>
                  <div class="flex items-center">
                    <span>{{ config.name }}</span>
                    <el-tag
                      :type="
                        config.fileType === 'score' ? 'warning' : 'primary'
                      "
                      size="small"
                      class="ml-2"
                    >
                      {{ config.fileType === "score" ? "比分" : "首页" }}
                    </el-tag>
                  </div>
                  <div class="text-sm text-gray-500">
                    {{ config.description }}
                  </div>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="文件日期" prop="fileDate">
          <el-date-picker
            v-model="formData.fileDate"
            type="date"
            placeholder="请选择文件日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="自定义文件路径">
          <el-input
            v-model="formData.customFilePath"
            placeholder="可选：指定具体的文件路径"
            clearable
          >
            <template #prepend>
              <el-icon><Folder /></el-icon>
            </template>
          </el-input>
          <div class="text-sm text-gray-500 mt-1">
            如果不填写，将使用配置中的默认路径
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="importing" @click="handleImport">
            <el-icon><Upload /></el-icon>
            开始导入
          </el-button>
          <el-button @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 导入历史记录 -->
    <el-card class="mt-4" v-if="importHistory.length > 0">
      <template #header>
        <span>最近导入记录</span>
      </template>

      <el-timeline>
        <el-timeline-item
          v-for="(record, index) in importHistory"
          :key="index"
          :type="record.success ? 'success' : 'danger'"
          :timestamp="record.timestamp"
        >
          <div>
            <div class="font-medium">
              {{ record.configName }} - {{ record.fileDate }}
            </div>
            <div class="text-sm text-gray-600">
              {{ record.success ? "导入成功" : "导入失败" }}
              {{ record.message ? `: ${record.message}` : "" }}
            </div>
            <div v-if="record.customFilePath" class="text-xs text-gray-500">
              文件路径: {{ record.customFilePath }}
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { ElMessage, type FormInstance, type FormRules } from "element-plus";
import { Folder, Upload } from "@element-plus/icons-vue";
import {
  getImportConfigs,
  importScoreFile,
  importHomepageFile,
  type ImportConfig,
  type ImportScoreParams,
  type ImportHomepageParams
} from "@/api/automation";
// 移除AutomationNav导入，现在由父页面统一管理
import { formatDateTime } from "@/utils/formatTime";

// 表单引用
const formRef = ref<FormInstance>();

// 响应式数据
const configLoading = ref(false);
const importing = ref(false);
const configList = ref<ImportConfig[]>([]);

// 表单数据
const formData = reactive<ImportScoreParams & ImportHomepageParams>({
  configId: "",
  fileDate: "",
  customFilePath: ""
});

// 导入历史记录类型
interface ImportRecord {
  configName: string;
  fileDate: string;
  customFilePath?: string;
  success: boolean;
  message?: string;
  timestamp: string;
}

// 导入历史记录
const importHistory = ref<ImportRecord[]>([]);

// 表单验证规则
const formRules: FormRules = {
  configId: [{ required: true, message: "请选择导入配置", trigger: "change" }],
  fileDate: [{ required: true, message: "请选择文件日期", trigger: "change" }]
};

// 获取导入配置列表
const fetchConfigs = async () => {
  try {
    configLoading.value = true;
    const response = await getImportConfigs();
    if (response.code === 0) {
      configList.value = response.data.filter(config => config.isEnabled);
    } else {
      ElMessage.error(response.message || "获取配置列表失败");
    }
  } catch (error) {
    console.error("获取配置列表失败:", error);
    ElMessage.error("获取配置列表失败");
  } finally {
    configLoading.value = false;
  }
};

// 处理导入
const handleImport = async () => {
  if (!formRef.value) return;

  try {
    const valid = await formRef.value.validate();
    if (!valid) return;

    importing.value = true;

    // 获取选中的配置
    const selectedConfig = configList.value.find(
      config => config.id!.toString() === formData.configId
    );

    if (!selectedConfig) {
      ElMessage.error("未找到选中的配置");
      return;
    }

    const importData = {
      configId: formData.configId,
      fileDate: formData.fileDate,
      customFilePath: formData.customFilePath || undefined
    };

    // 根据配置类型调用不同的API
    const response =
      selectedConfig.fileType === "score"
        ? await importScoreFile(importData)
        : await importHomepageFile(importData);

    // 添加到历史记录
    const record: ImportRecord = {
      configName: selectedConfig.name,
      fileDate: formData.fileDate,
      customFilePath: formData.customFilePath,
      success: response.code === 0,
      message: response.message,
      timestamp: formatDateTime(new Date(), "YYYY-MM-DD HH:mm:ss")
    };

    importHistory.value.unshift(record);

    // 只保留最近10条记录
    if (importHistory.value.length > 10) {
      importHistory.value = importHistory.value.slice(0, 10);
    }

    if (response.code === 0) {
      ElMessage.success("导入成功");
      handleReset();
    } else {
      ElMessage.error(response.message || "导入失败");
    }
  } catch (error: any) {
    console.error("导入失败:", error);

    // 提取错误信息
    let errorMessage = "网络错误或服务异常";
    if (error?.response?.data?.message) {
      errorMessage = error.response.data.message;
    } else if (error?.message) {
      errorMessage = error.message;
    }

    ElMessage.error(errorMessage);

    // 添加失败记录
    const selectedConfig = configList.value.find(
      config => config.id!.toString() === formData.configId
    );

    const record: ImportRecord = {
      configName: selectedConfig?.name || "未知配置",
      fileDate: formData.fileDate,
      customFilePath: formData.customFilePath,
      success: false,
      message: errorMessage,
      timestamp: formatDateTime(new Date(), "YYYY-MM-DD HH:mm:ss")
    };

    importHistory.value.unshift(record);
  } finally {
    importing.value = false;
  }
};

// 重置表单
const handleReset = () => {
  formData.configId = "";
  formData.fileDate = "";
  formData.customFilePath = "";
  formRef.value?.clearValidate();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchConfigs();
});
</script>

<style scoped>
.automation-import {
  padding: 20px;
}

.text-sm {
  font-size: 14px;
}

.text-xs {
  font-size: 12px;
}

.text-gray-500 {
  color: #6b7280;
}

.text-gray-600 {
  color: #4b5563;
}

.font-medium {
  font-weight: 500;
}

.mt-1 {
  margin-top: 4px;
}

.mt-4 {
  margin-top: 16px;
}
</style>
